package com.borrowed.book.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.borrowed.book.book.Exception.UnexpectOrderException;
import com.borrowed.book.book.constant.BookConstant;
import com.borrowed.book.book.domain.*;
import com.borrowed.book.book.entity.domain.vo.PayOrderBaseInVo;
import com.borrowed.book.book.entity.domain.vo.PayOrderBaseOutVo;
import com.borrowed.book.book.entity.domain.vo.PayOrderCreateInVo;
import com.borrowed.book.book.mapper.SPayOrderDetailMapper;
import com.borrowed.book.book.mapper.SPayOrderMapper;
import com.borrowed.book.book.service.AbstractPayOrderService;
import com.borrowed.book.book.util.PayorderUtil;
import com.borrowed.book.coupon.entity.SCoupon;
import com.borrowed.book.coupon.service.SCouponService;
import com.borrowed.book.coupon.service.SCouponUserService;
import com.borrowed.book.membercard.entity.SMemberCard;
import com.borrowed.book.membercard.service.SMemberCardService;
import com.borrowed.book.membercard.service.SMembercardUserService;
import com.borrowed.book.system.util.DayUtil;
import com.borrowed.book.user.domain.SUser;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 会员卡订单类
 */
@Service
public class CardPayorerServiceImpl extends AbstractPayOrderService {
    @Autowired
    private SMemberCardService memberCardService;//会员卡服务
    @Autowired
    private SMembercardUserService membercardUserService;
    @Autowired
    private SCouponService couponService;  //优惠券服务
    @Autowired
    private SCouponUserService couponUserService;
    @Autowired
    private SPayOrderMapper payOrderMapper;
    @Autowired
    private SPayOrderDetailMapper payOrderDetailMapper;
    /**
     * 会员订单下单前数据加载
     * @param payorderBaseInVo
     * @return
     */
    @Override
    public PayOrderBaseOutVo initialPayorderInfo(PayOrderBaseInVo payorderBaseInVo) {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        InitialCarPayInDto param=(InitialCarPayInDto)payorderBaseInVo;

        SMemberCard carInfo=memberCardService.getById(param.getCardId());
        InitialCardPayDtoOut cardPay= PayorderUtil.getComplexDate(carInfo);
        /**
         * 年会员，才可以使用优惠券功能
         */
        if (BookConstant.TIME_UNIT_YEAR.equals(carInfo.getValidTimeUnit())) {
            if(param.getCouponId()==null) {
                //年会会员，查询对应的有效的优惠券
                if(param.getUseCoupon()) {
                    SelectUserCouponInDto couponInDto=new SelectUserCouponInDto();
                    couponInDto.setCouponStatus(BookConstant.COUPON_STATUS_UNUSE);
                    couponInDto.setCouponType( BookConstant.COUPON_TYPE_TWO);
                    List<SCouponDto>  couponList=couponService.selectUserCoupon(couponInDto);
                    if (couponList != null&&couponList.size()>0) {
                        couponList.get(0).setRemainDays(DayUtil.daysBetween(new Date(), couponList.get(0).getValidEndTime()));
                        cardPay.setScoupon(couponList.get(0));
                        cardPay.setSettlePrice(carInfo.getCardPrice().subtract(couponList.get(0).getFaceValue()));
                    }
                }
            }else{
                //传入选中的优惠券，重新计算结算价格
                SCoupon coupon =couponService.getById(param.getCouponId());
                SCouponDto couponDto=new SCouponDto();
                BeanUtils.copyProperties(coupon,couponDto);
                couponDto.setRemainDays(DayUtil.daysBetween(new Date(), coupon.getValidEndTime()));
                cardPay.setScoupon(couponDto);
                cardPay.setSettlePrice(carInfo.getCardPrice().subtract(coupon.getFaceValue()));
            }
        }
        return cardPay;
    }

    /**
     * 创建会员卡订单
     * @param payOrderCreateInVo
     * @return
     */
    @Override
    public String createPayorder(PayOrderCreateInVo payOrderCreateInVo) throws UnexpectOrderException {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        PayOrderInDto param=(PayOrderInDto)payOrderCreateInVo;
        //如果使用了优惠券，更新优惠券状态为使用中
        if(param.getCouponId()!=null){
            UpdateWrapper updateWrapper=new UpdateWrapper();
            updateWrapper.eq("id",param.getCouponId());
            updateWrapper.set("coupon_status",BookConstant.COUPON_STATUS_INUSE);
            couponUserService.update(updateWrapper);
        }
        //创建订单编号
        String orderNo=PayorderUtil.createOrderNo();
        SPayOrder payOrder=new SPayOrder();
        BeanUtils.copyProperties(param,payOrder);
        payOrder.setOpenid(sysUser.getOpenid());
        payOrder.setOrderNo(orderNo);
        payOrder.setOrderStatus(BookConstant.UN_PAY);
        payOrder.setCreateTime(new Date());
        payOrderMapper.insert(payOrder);
        //插入订单详细数据
        //会员卡订单
        SMemberCard cardInfo=memberCardService.getById(param.getCardId());
        SPayOrderDetail payOrderDetail=new SPayOrderDetail();
        payOrderDetail.setGoodId(param.getCardId());
        payOrderDetail.setOrderNo(orderNo);
        payOrderDetail.setGoodPrice(cardInfo.getCardPrice());
        payOrderDetailMapper.insert(payOrderDetail);
        return orderNo;
    }

    /**
     * 取消订单
     * @param orderNo
     * @return
     */
    @Override
    public Boolean cancelPayorder(String orderNo) {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        SelectPayOrderOutDto orderInfo=payOrderMapper.selectPayOrderById(orderNo);
        //优惠券  状态更新为待使用
        if(orderInfo.getCouponId()!=null) {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", orderInfo.getCouponId());
            updateWrapper.set("coupon_status", BookConstant.COUPON_STATUS_UNUSE);
            couponUserService.update(updateWrapper);
        }
        //解绑优惠券id,订单状态更新为已取消
        Map<String,Object> map=new HashMap<>();
        map.put("openid",sysUser.getOpenid());
        map.put("orderNo",orderNo);
        map.put("payStatus",BookConstant.CANCELL_PAY);
        payOrderMapper.cancelPayOrder(map);
        return true;
    }
}
